package com.qf.commons.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 配置Spring内部的线程池对象
 */
@Configuration
public class AsyncConfiguration implements AsyncConfigurer {

    /**
     * 注册线程池
     * @return
     */
    @Bean
    public ThreadPoolTaskExecutor getThreadPoolTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数 - CPU核心数的 2~3倍
        //IO密集型 - 线程数 = CPU核心数 * 2~3
        //CPU密集型 - 线程数 = CPU核心数
        // CPU核心数 - 灶台
        // 线程数 - 厨师
        int core = Runtime.getRuntime().availableProcessors();//CPU核心数
        threadPoolTaskExecutor.setCorePoolSize(core * 3);
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(core * 4);
        //非核心线程的存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        //阻塞队列的最大容量
        threadPoolTaskExecutor.setQueueCapacity(10000);
        //设置线程名称的前缀
        threadPoolTaskExecutor.setThreadNamePrefix("myThread-");
        //线程初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    /**
     * 设置定义的线程池 替换Spring内容的线程池
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        return getThreadPoolTaskExecutor();
    }
}
